function maxTotalFruits(fruits, startPos, k) {
  let maxFruits = 0;
  const n = fruits.length;
  let left = 0;
  let currentFruits = 0;

  // 过滤掉明显无法到达的水果，提高效率
  while (left < n && fruits[left][0] < startPos - k) {
    left++;
  }

  for (
    let right = left;
    right < n && fruits[right][0] <= startPos + k;
    right++
  ) {
    currentFruits += fruits[right][1];

    // 当窗口内的水果无法在k步内全部收集时，移动左指针
    while (!canCollect(fruits, left, right, startPos, k)) {
      currentFruits -= fruits[left][1];
      left++;
    }

    maxFruits = Math.max(maxFruits, currentFruits);
  }

  return maxFruits;
}

// 判断是否能在k步内收集[left, right]范围内的所有水果
function canCollect(fruits, left, right, startPos, k) {
  const leftPos = fruits[left][0];
  const rightPos = fruits[right][0];

  // 所有水果都在startPos左侧
  if (rightPos <= startPos) {
    return startPos - leftPos <= k;
  }
  // 所有水果都在startPos右侧
  else if (leftPos >= startPos) {
    return rightPos - startPos <= k;
  }
  // 水果在startPos两侧
  else {
    const stepsLeftThenRight = startPos - leftPos + (rightPos - leftPos);
    const stepsRightThenLeft = rightPos - startPos + (rightPos - leftPos);
    return Math.min(stepsLeftThenRight, stepsRightThenLeft) <= k;
  }
}
